﻿using System;
using System.Collections.Generic;
using System.Data;
using SdmxMl.Common;
using SdmxMl.Manager;
using SdmxMl.Structure;

namespace SdmxMl.SanteSuisse
{
    public class QuestProcess
    {
        private ConceptSchemeType _cst;
        private ProcessType _process;

        public QuestProcess (ConceptSchemeType cst)
        {
            _cst = cst;
            _process = new ProcessType();
            _process.Id = "P_" + _cst.Id.Substring(3);
            _process.AgencyId = _cst.AgencyId;
            _process.Name.UpdateDefaultText("Process of " + _cst.Name.ToString());
        }

        private void CompleteTransition(ProcessStepType pstPrev, ProcessStepType pstCur, ConceptType cPrev)
        {
            // Transition to current
            if (pstPrev != null)
            {
                TransitionType tr = new TransitionType();
                tr.TargetStep = pstCur.Id;
                tr.Condition.UpdateDefaultText("Normal");
                pstPrev.TransitionList.Add(tr);

                // Transitions due to answer code
                AnnotationList annList = cPrev.AnnotationList.GetAllAnnotationOfType("CODE_CONTINUE", null);
                foreach (Annotation an in annList)
                {
                    tr = new TransitionType();
                    tr.TargetStep =an.Text.ToString();
                    tr.Condition.UpdateDefaultText("Code: " + an.Title);
                    pstPrev.TransitionList.Add(tr);
                }
            }
        }

        private void GenerateProcessStep(ConceptList cl)
        {
            ProcessStepType pstPrev = null;
            ConceptType cPrev = null;

            foreach (ConceptType c in cl)
            {
                string na = c.Name.ToString();
                if (na.Length >= 2 && na.Length < 6)
                {
                    Annotation ann = c.AnnotationList.GetAnnotationType("QUESTION", 1);
                    if (ann != null)
                    {
                        ProcessStepType pst = new ProcessStepType(_process.ProcessStepList, null);
                        pst.Id = c.Name.ToString();
                        pst.Name.UpdateDefaultText(c.Id);
                        pst.Description = ann.Text.Clone();
                        ann = c.AnnotationList.GetAnnotationType("INT", 1);
                        if (ann != null)
                            pst.Computation = ann.Text.Clone();
                        
                        _process.ProcessStepList.Add(pst);

                        CompleteTransition(pstPrev, pst, cPrev);

                        pstPrev = pst;
                        cPrev = c;
                    }
                }
            }
        }
    }
}
